// RBAC权限管理系统
// 角色：院长(dean)、主任(director)、医生(doctor)、护士(nurse)
// 超级管理员(super_admin)拥有所有权限

export enum UserRole {
  SUPER_ADMIN = 'super_admin',    // 超级管理员
  DEAN = 'dean',                  // 院长
  DIRECTOR = 'director',          // 主任
  DOCTOR = 'doctor',              // 医生
  NURSE = 'nurse'                 // 护士
}

export enum Permission {
  // 仪表板权限
  VIEW_DASHBOARD = 'view_dashboard',
  
  // 实时监控权限
  VIEW_REALTIME_DATA = 'view_realtime_data',
  VIEW_SYSTEM_STATUS = 'view_system_status',
  VIEW_DEVICE_MONITORING = 'view_device_monitoring',
  
  // 数据分析权限
  VIEW_ANALYTICS = 'view_analytics',
  VIEW_PATIENT_MANAGEMENT = 'view_patient_management',
  VIEW_DEPARTMENT_MANAGEMENT = 'view_department_management',
  EDIT_PATIENT_INFO = 'edit_patient_info',
  EDIT_DEPARTMENT_INFO = 'edit_department_info',
  
  // 优化方案权限
  VIEW_OPTIMIZATION = 'view_optimization',
  CREATE_OPTIMIZATION = 'create_optimization',
  APPROVE_OPTIMIZATION = 'approve_optimization',
  
  // 场景库权限
  VIEW_SCENARIOS = 'view_scenarios',
  CREATE_SCENARIOS = 'create_scenarios',
  EDIT_SCENARIOS = 'edit_scenarios',
  DELETE_SCENARIOS = 'delete_scenarios',
  
  // 系统管理权限（仅超级管理员）
  MANAGE_PERMISSIONS = 'manage_permissions',
  MANAGE_USERS = 'manage_users',
  SYSTEM_SETTINGS = 'system_settings'
}

// 角色权限映射
export const RolePermissions: Record<UserRole, Permission[]> = {
  [UserRole.SUPER_ADMIN]: [
    // 超级管理员拥有所有权限
    Permission.VIEW_DASHBOARD,
    Permission.VIEW_REALTIME_DATA,
    Permission.VIEW_SYSTEM_STATUS,
    Permission.VIEW_DEVICE_MONITORING,
    Permission.VIEW_ANALYTICS,
    Permission.VIEW_PATIENT_MANAGEMENT,
    Permission.VIEW_DEPARTMENT_MANAGEMENT,
    Permission.EDIT_PATIENT_INFO,
    Permission.EDIT_DEPARTMENT_INFO,
    Permission.VIEW_OPTIMIZATION,
    Permission.CREATE_OPTIMIZATION,
    Permission.APPROVE_OPTIMIZATION,
    Permission.VIEW_SCENARIOS,
    Permission.CREATE_SCENARIOS,
    Permission.EDIT_SCENARIOS,
    Permission.DELETE_SCENARIOS,
    Permission.MANAGE_PERMISSIONS,
    Permission.MANAGE_USERS,
    Permission.SYSTEM_SETTINGS
  ],
  
  [UserRole.DEAN]: [
    // 院长：全局管理权限，但不能管理系统权限
    Permission.VIEW_DASHBOARD,
    Permission.VIEW_REALTIME_DATA,
    Permission.VIEW_SYSTEM_STATUS,
    Permission.VIEW_DEVICE_MONITORING,
    Permission.VIEW_ANALYTICS,
    Permission.VIEW_PATIENT_MANAGEMENT,
    Permission.VIEW_DEPARTMENT_MANAGEMENT,
    Permission.EDIT_DEPARTMENT_INFO,
    Permission.VIEW_OPTIMIZATION,
    Permission.CREATE_OPTIMIZATION,
    Permission.APPROVE_OPTIMIZATION,
    Permission.VIEW_SCENARIOS,
    Permission.CREATE_SCENARIOS,
    Permission.EDIT_SCENARIOS
  ],
  
  [UserRole.DIRECTOR]: [
    // 主任：科室管理权限
    Permission.VIEW_DASHBOARD,
    Permission.VIEW_REALTIME_DATA,
    Permission.VIEW_ANALYTICS,
    Permission.VIEW_PATIENT_MANAGEMENT,
    Permission.VIEW_DEPARTMENT_MANAGEMENT,
    Permission.EDIT_PATIENT_INFO,
    Permission.VIEW_OPTIMIZATION,
    Permission.VIEW_SCENARIOS,
    Permission.CREATE_SCENARIOS
  ],
  
  [UserRole.DOCTOR]: [
    // 医生：患者管理和查看权限
    Permission.VIEW_DASHBOARD,
    Permission.VIEW_REALTIME_DATA,
    Permission.VIEW_ANALYTICS,
    Permission.VIEW_PATIENT_MANAGEMENT,
    Permission.EDIT_PATIENT_INFO,
    Permission.VIEW_SCENARIOS
  ],
  
  [UserRole.NURSE]: [
    // 护士：基础查看和患者信息权限
    Permission.VIEW_DASHBOARD,
    Permission.VIEW_REALTIME_DATA,
    Permission.VIEW_PATIENT_MANAGEMENT,
    Permission.EDIT_PATIENT_INFO
  ]
}

// 权限检查函数
export class PermissionChecker {
  /**
   * 检查用户是否有指定权限
   * @param userRole 用户角色
   * @param permission 权限
   * @param userId 用户ID（可选，用于检查自定义权限）
   * @returns 是否有权限
   */
  static hasPermission(userRole: UserRole, permission: Permission, userId?: string): boolean {
    const rolePermissions = RolePermissions[userRole] || []
    
    // 检查角色默认权限
    if (rolePermissions.includes(permission)) {
      return true
    }
    
    // 检查用户自定义权限
    if (userId) {
      const customPermissions = this.getUserCustomPermissions(userId)
      return customPermissions.includes(permission)
    }
    
    return false
  }

  /**
   * 获取用户自定义权限
   * @param userId 用户ID
   * @returns 自定义权限列表
   */
  static getUserCustomPermissions(userId: string): Permission[] {
    try {
      const stored = localStorage.getItem(`user_permissions_${userId}`)
      return stored ? JSON.parse(stored) : []
    } catch {
      return []
    }
  }

  /**
   * 检查用户是否可以访问指定页面
   * @param userRole 用户角色
   * @param page 页面标识
   * @param userId 用户ID（可选，用于检查自定义权限）
   * @returns 是否可以访问
   */
  static canAccessPage(userRole: UserRole, page: string, userId?: string): boolean {
    const pagePermissionMap: Record<string, Permission> = {
      'dashboard': Permission.VIEW_DASHBOARD,
      'realtime': Permission.VIEW_REALTIME_DATA,
      'system': Permission.VIEW_SYSTEM_STATUS,
      'devices': Permission.VIEW_DEVICE_MONITORING,
      'analytics': Permission.VIEW_ANALYTICS,
      'patients': Permission.VIEW_PATIENT_MANAGEMENT,
      'departments': Permission.VIEW_DEPARTMENT_MANAGEMENT,
      'optimization': Permission.VIEW_OPTIMIZATION,
      'scenarios': Permission.VIEW_SCENARIOS,
      'permissions': Permission.MANAGE_PERMISSIONS, // 只有超级管理员可访问
      'users': Permission.MANAGE_USERS,
      'settings': Permission.SYSTEM_SETTINGS
    }

    const requiredPermission = pagePermissionMap[page]
    if (!requiredPermission) return false
    
    // 特殊逻辑：场景库页面的访问权限
    if (page === 'scenarios') {
      // 拥有任何场景相关权限的用户都能访问场景库页面
      return this.hasPermission(userRole, Permission.VIEW_SCENARIOS, userId) ||
             this.hasPermission(userRole, Permission.CREATE_SCENARIOS, userId) ||
             this.hasPermission(userRole, Permission.EDIT_SCENARIOS, userId) ||
             this.hasPermission(userRole, Permission.DELETE_SCENARIOS, userId)
    }
    
    return this.hasPermission(userRole, requiredPermission, userId)
  }

  /**
   * 获取用户可访问的菜单项
   * @param userRole 用户角色
   * @param userId 用户ID（可选，用于检查自定义权限）
   * @returns 可访问的菜单项列表
   */
  static getAccessibleMenus(userRole: UserRole, userId?: string): string[] {
    const allMenus = [
      'dashboard',
      'realtime', 
      'system',
      'devices',
      'analytics',
      'patients',
      'departments',
      'optimization',
      'scenarios'
    ]

    // 只有超级管理员才能看到权限管理
    if (userRole === UserRole.SUPER_ADMIN) {
      allMenus.push('permissions', 'users', 'settings')
    }

    return allMenus.filter(menu => this.canAccessPage(userRole, menu, userId))
  }

  /**
   * 获取角色的所有权限
   * @param userRole 用户角色
   * @returns 权限列表
   */
  static getRolePermissions(userRole: UserRole): Permission[] {
    return RolePermissions[userRole] || []
  }

  /**
   * 检查是否为超级管理员
   * @param userRole 用户角色
   * @returns 是否为超级管理员
   */
  static isSuperAdmin(userRole: UserRole): boolean {
    return userRole === UserRole.SUPER_ADMIN
  }
}

// 用户角色显示名称映射
export const RoleDisplayNames: Record<UserRole, { zh: string; en: string }> = {
  [UserRole.SUPER_ADMIN]: { zh: '超级管理员', en: 'Super Admin' },
  [UserRole.DEAN]: { zh: '院长', en: 'Dean' },
  [UserRole.DIRECTOR]: { zh: '主任', en: 'Director' },
  [UserRole.DOCTOR]: { zh: '医生', en: 'Doctor' },
  [UserRole.NURSE]: { zh: '护士', en: 'Nurse' }
}

// 权限显示名称映射
export const PermissionDisplayNames: Record<Permission, { zh: string; en: string }> = {
  [Permission.VIEW_DASHBOARD]: { zh: '查看仪表板', en: 'View Dashboard' },
  [Permission.VIEW_REALTIME_DATA]: { zh: '查看实时数据', en: 'View Realtime Data' },
  [Permission.VIEW_SYSTEM_STATUS]: { zh: '查看系统状态', en: 'View System Status' },
  [Permission.VIEW_DEVICE_MONITORING]: { zh: '设备监控', en: 'Device Monitoring' },
  [Permission.VIEW_ANALYTICS]: { zh: '数据分析', en: 'View Analytics' },
  [Permission.VIEW_PATIENT_MANAGEMENT]: { zh: '患者管理', en: 'Patient Management' },
  [Permission.VIEW_DEPARTMENT_MANAGEMENT]: { zh: '科室管理', en: 'Department Management' },
  [Permission.EDIT_PATIENT_INFO]: { zh: '编辑患者信息', en: 'Edit Patient Info' },
  [Permission.EDIT_DEPARTMENT_INFO]: { zh: '编辑科室信息', en: 'Edit Department Info' },
  [Permission.VIEW_OPTIMIZATION]: { zh: '优化方案', en: 'View Optimization' },
  [Permission.CREATE_OPTIMIZATION]: { zh: '创建优化方案', en: 'Create Optimization' },
  [Permission.APPROVE_OPTIMIZATION]: { zh: '审批优化方案', en: 'Approve Optimization' },
  [Permission.VIEW_SCENARIOS]: { zh: '场景库', en: 'View Scenarios' },
  [Permission.CREATE_SCENARIOS]: { zh: '创建场景', en: 'Create Scenarios' },
  [Permission.EDIT_SCENARIOS]: { zh: '编辑场景', en: 'Edit Scenarios' },
  [Permission.DELETE_SCENARIOS]: { zh: '删除场景', en: 'Delete Scenarios' },
  [Permission.MANAGE_PERMISSIONS]: { zh: '权限管理', en: 'Manage Permissions' },
  [Permission.MANAGE_USERS]: { zh: '用户管理', en: 'Manage Users' },
  [Permission.SYSTEM_SETTINGS]: { zh: '系统设置', en: 'System Settings' }
}

// 导出类型
export type UserPermissions = Permission[]
export type RolePermissionMap = typeof RolePermissions